package cn.birdbaby.plugins.selector.clazz;

import cn.birdbaby.plugins.constants.Constants;
import com.intellij.openapi.application.ReadAction;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiJavaCodeReferenceElement;
import com.intellij.psi.util.PsiTreeUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.Collection;

/**
 * @author llorando 9/8/24 3:44 pm
 * 选择需要添加FieldDesc注解的类
 */
public class EntitySelector extends PsiClassSelector {
    @Override
    public boolean match(PsiElement psiElement) {
        Collection<PsiAnnotation> childrenOfAnyType = PsiTreeUtil.findChildrenOfAnyType(psiElement, PsiAnnotation.class);
        if(childrenOfAnyType.isEmpty()) return false;

        for(PsiAnnotation psiAnnotation:childrenOfAnyType){
            String referenceName = ReadAction.compute(() -> {
                PsiJavaCodeReferenceElement nameReferenceElement = psiAnnotation.getNameReferenceElement();
                return nameReferenceElement.getReferenceName();
            });

            if (StringUtils.startsWithIgnoreCase(referenceName, Constants.AnnotationName.ENTITY) || StringUtils.startsWithIgnoreCase(referenceName, Constants.AnnotationName.TABLE)) {
                return true;
            }
        }
        return false;
    }


    @Override
    public String getName() {
        return Constants.AnnotationName.ENTITY;
    }
}
